import { useMemo } from 'react'
import Chart from '@/pages/bi-core/Chart'
import { Radio, Button, InputNumber } from 'antd'
import QueryFields from './QueryFields'
import styles from './index.module.less'

const DataQuery = ({ selectedWidget, value: query, onChange, onUpdate }) => {
  const requestFields = useMemo(
    () => ({
      ...Chart.getRequestFields(selectedWidget.type),
      filter: {
        limit: -1,
        role: 'filter',
        label: '过滤器'
      }
    }),
    [selectedWidget]
  )

  const aggrModeEnabled = useMemo(
    () => Chart.getProperty(selectedWidget.type, 'aggrModeEnabled', false),
    [selectedWidget]
  )

  const findField = (id, key) => {
    const queryField = query.queryFields[key] || []
    return {
      field: queryField.find((v) => v.id === id),
      index: queryField.findIndex((v) => v.id === id)
    }
  }

  const moveField = (draggedField, draggedIndex, droppedIndex, key) => {
    const queryField = [...query.queryFields[key]]
    if (queryField.length) {
      queryField.splice(draggedIndex, 1)
      queryField.splice(droppedIndex, 0, draggedField)
      const newQuery = {
        ...query,
        queryFields: {
          ...query.queryFields,
          [key]: queryField
        }
      }
      onChange(newQuery)
    }
  }

  const onQueryFieldsChange = (item, key) => {
    const queryField = query.queryFields[key] || []
    const newQuery = {
      ...query,
      queryFields: {
        ...query.queryFields,
        [key]: [...queryField, item]
      }
    }
    onChange(newQuery)
  }

  const onQueryChange = (val, attr) => {
    const newQuery = { ...query, [attr]: val }
    onChange(newQuery)
  }

  const aggOptions = [
    { label: '聚合', value: 'sum' },
    { label: '明细', value: 'detail' }
  ]

  return (
    <div className={styles['data-query']}>
      <QueryFields
        requestFields={requestFields}
        value={query.queryFields}
        onChange={onQueryFieldsChange}
        findField={findField}
        moveField={moveField}
      />
      <div className={styles['query-config']}>
        <div className={styles['result']}>
          <label>结果展示</label>
          <InputNumber
            value={query.limit}
            onChange={(val) => onQueryChange(val, 'limit')}
            size="small"
          />
        </div>
        {aggrModeEnabled ? (
          <Radio.Group
            className={styles['agg']}
            value={query.aggrMode}
            onChange={(e) => onQueryChange(e.target.value, 'aggrMode')}
            buttonStyle="solid"
            size="small"
            options={aggOptions}
            optionType="button"
          />
        ) : null}
        <Button onClick={onUpdate} className={styles['update']} type="primary">
          更新
        </Button>
      </div>
    </div>
  )
}

export default DataQuery
